package com.akk.module.avs.service;

import com.akk.module.avs.entity.AvsYbCard;
import com.akk.module.avs.entity.AvsYbCardExample;
import com.akk.module.avs.entity.AvsYbCardTagsExample;
import com.akk.module.avs.mapper.AvsYbCardMapper;
import com.akk.module.avs.mapper.AvsYbCardTagsMapper;
import com.akk.module.avs.mapper.dao.AvsYbCardDao;
import com.akk.module.avs.mapper.dao.AvsYbCardTagsDao;
import com.akk.module.avs.mapper.dao.AvsYbTagsDao;
import com.akk.module.avs.model.response.AvsYbCardMatchRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AvsYbCardService {

    @Autowired
    private AvsYbCardExample cardExample;

    @Autowired
    private AvsYbCardMapper cardMapper;

    @Autowired
    private AvsYbCardTagsDao cardTagsDao;

    @Autowired
    private AvsYbCardTagsMapper cardTagsMapper;

    @Autowired
    private AvsYbCardTagsExample cardTagsExample;

    @Autowired
    private AvsYbCardDao cardDao;

    public List<AvsYbCard> findByParams(Map params){
        cardExample.clear();
        AvsYbCardExample.Criteria criteria = cardExample.createCriteria();
        if (params.containsKey("status"))
            criteria.andStatusEqualTo(Integer.valueOf(params.get("status").toString()));
        if (params.containsKey("appId"))
            criteria.andAppIdEqualTo(params.get("appId").toString());
        return cardMapper.selectByExample(cardExample);
    }

    public AvsYbCard findById(Long cardId){
        return cardMapper.selectByPrimaryKey(cardId);
    }

    @Transactional
    public Long save(AvsYbCard card,List<Integer> tags){
        cardMapper.insert(card);
        Map params = new HashMap();
        params.put("tags",tags);
        params.put("cardId",card.getCardId());
        cardTagsDao.insertBatch(params);
        return card.getCardId();
    }

    @Transactional
    public void update(AvsYbCard card,List<Integer> tags){
        cardTagsExample.clear();
        cardTagsExample.createCriteria().andCardIdEqualTo(card.getCardId());
        cardTagsMapper.deleteByExample(cardTagsExample);
        Map params = new HashMap();
        params.put("tags",tags);
        params.put("cardId",card.getCardId());
        cardTagsDao.insertBatch(params);
        cardMapper.updateByPrimaryKey(card);
    }

    public void del(Long cardId){
        cardMapper.deleteByPrimaryKey(cardId);
    }

    public List<AvsYbCard> queryTop5(String appId){
        return cardDao.selectTop5(appId);
    }

    public List<AvsYbCardMatchRes> seletMatch(Map params){
        return cardDao.selectContainTag(params);
    }

    public List<AvsYbCardMatchRes> seletMatchTop5(Map params){
        return cardDao.selectContainTagTop5(params);
    }

}
